import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false })
const whiteList = ['/login', '/auth-redirect', '/loading-module']
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title);
  const hasToken = getToken();
  const organizationNo = sessionStorage.organizationNo;
  const username = sessionStorage.username;
  if (hasToken && organizationNo && username) {
    if (to.path === '/login') {
      next()
      NProgress.done()
    } else {
      const topOrganizationNo = store.getters.topOrganizationNo
      if (topOrganizationNo || whiteList.indexOf(to.path) !== -1) {
        next()
      } else {
        try {
          await store.dispatch('user/getTopOrganization')
          await store.dispatch('user/getUserMenu')
          const accessRoutes = await store.dispatch('permission/generateRoutes', 'admin')
          console.log('accessRoutes', accessRoutes)
          router.addRoutes(accessRoutes)
          next({ ...to, replace: true })
        } catch (error) {
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
